package cn.lovelysia.ymcc.service.impl;

import cn.lovelysia.ymcc.domain.CourseType;
import cn.lovelysia.ymcc.mapper.CourseTypeMapper;
import cn.lovelysia.ymcc.service.ICourseTypeService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 课程目录 服务实现类
 * </p>
 *
 * @author elysia
 * @since 2022-12-06
 */
@Service
public class CourseTypeServiceImpl extends ServiceImpl<CourseTypeMapper, CourseType> implements ICourseTypeService {

    @Autowired
    private CourseTypeMapper courseTypeMapper;
    @Resource
    private RedisTemplate<String,List<CourseType>> redisTemplate;

    @Override
    @Cacheable(cacheNames = "treeData",key = "'ALL'")
    public List<CourseType> treeData() {

        String key = "treeData";
        List<CourseType> list = redisTemplate.opsForValue().get(key);
        if(list==null){
            List<CourseType> courseTypes = courseTypeMapper.selectList(null);
            //将所有课程类型查出来，放到map中
            HashMap<Long, CourseType> map = new HashMap<>();
            for (CourseType courseType : courseTypes) {
                map.put(courseType.getId(),courseType);
            }
            List<CourseType> treeData = new ArrayList<>();
            //遍历map 放到 treeData中
            for (CourseType courseType : courseTypes) {
                if(courseType.getPid()==0){
                    treeData.add(courseType);
                }else {
                    //获取父类型
                    Long parentId = courseType.getPid();
                    CourseType parentCourseType = map.get(parentId);
                    if(parentCourseType!=null){
                        //添加到父类型的子集合
                        parentCourseType.getChildren().add(courseType);
                    }
                }
            }
            redisTemplate.opsForValue().set(key,treeData,24, TimeUnit.HOURS);
            return treeData;
        }
        return list;
    }

    @Override
    @Cacheable(cacheNames = "treeData",key = "'ALL'")
    public boolean deleteById(Serializable id) {
        boolean b = super.deleteById(id);
//        if(b){
//            redisTemplate.delete("treeData");
//        }
        return b;
    }

    @Override
    @Cacheable(cacheNames = "treeData",key = "'ALL'")
    public boolean insert(CourseType entity) {
        return super.insert(entity);
    }

    @Override
    @Cacheable(cacheNames = "treeData",key = "'ALL'")
    public boolean updateById(CourseType entity) {
        return super.updateById(entity);
    }
}
